<template>
  <div>
    <a-form
      :model="formState"
      ref="formRef"
      name="validate_other"
      v-bind="formItemLayout"
      :rules="rules"
    >
      <a-row :gutter="50">
        <a-col :span="4">
          <a-form-item label="招标名称" name="title">
            <a-input
              v-model:value="formState.title"
              placeholder="请输入招标名称"
            >
            </a-input>
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="招标编号" name="code">
            <a-input
              v-model:value="formState.code"
              placeholder="请输入招标名称"
            >
            </a-input>
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="发布日期" name="time">
            <a-date-picker
              style="width: 100%"
              v-model:value="formState.time"
              placeholder="请选择发布日期"
            />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="所属地区" name="position">
            <a-cascader
              placeholder="请选择城市"
              v-model:value="formState.position"
              :options="areaTree?.[0]?.children"
              :fieldNames="{
                label: 'name',
                value: 'adcode',
                children: 'children',
              }"
            />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="采购类别" name="industry">
            <a-select
              v-model:value="formState.industry"
              placeholder="请选择采购类别"
            >
              <a-select-option
                :key="item.id"
                v-for="item in tags"
                :value="item.id"
                >{{ item.name }}</a-select-option
              >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="公告类型" name="infoid">
            <a-select
              v-model:value="formState.infoid"
              placeholder="请选择公告类型"
            >
              <a-select-option
                :key="item.infoid"
                v-for="item in type"
                :value="item.infoid"
                >{{ item.infoname }}</a-select-option
              >
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <div class="flex gap-[20px] items-center">
        <div
          style="
            width: 30px;
            height: 30px;
            background: #f43107;
            border-radius: 4px;
            font-size: 24px;
            color: #fff;
            text-align: center;
            line-height: 28px;
          "
        >
          +
        </div>

        <span>招标附件</span>

        <a-upload name="file" :before-upload="beforeUpload">
          <a-button type="primary"> 选择文件 </a-button>
          <template #itemRender="{ file, actions }">
            <!-- <a-space>
              <span>{{ file.name }}</span>
              <DeleteOutlined @click="actions.remove" />
            </a-space> -->
          </template>
        </a-upload>

        <a-space v-for="(file, index) in fileList" :key="file.url">
          <span>{{ file.name }}</span>
          <DeleteOutlined @click="remove(index)" />
        </a-space>
      </div>

      <div class="mt-[20px] overflow-y-auto">
        <!-- <QuillEditor
          style="height: 240px"
          toolbar="full"
          theme="snow"
          v-model:content="formState.content"
        >
        </QuillEditor> -->

        <VueUeditorWrap
          v-model="formState.content"
          :config="editorConfig"
          editor-id="editor-demo-01"
        ></VueUeditorWrap>
      </div>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import {
  searchgetInfomation,
  Inforeleasetags,
  Inforeleaseadd,
  Inforeleaseget_serial_number,
  Inforeleasedetail,
  Inforeleaseedit,
  upload,
} from "../../../../Api/work";
import area from "../../setup/info/areaCode.json";
import { message } from "ant-design-vue/es/components";
import { DeleteOutlined } from "@ant-design/icons-vue";
import dayjs from "dayjs";

const areaTree = ref([]);

// const editorConfig = {
//  // 访问 UEditor 静态资源的根路径，可参考常见问题1
//   serverUrl: "https://api.6ocbx.com/index/upload", // 服务端接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！）
// };

const editorConfig = {
  //是否开启字数统计
  wordCount: true,
  //允许输入的最大字符数
  maximumWords: 50000,
  // 编辑器不自动被内容撑高
  autoHeightEnabled: false,
  // 初始容器高度
  initialFrameHeight: 240,
  // 初始容器宽度
  initialFrameWidth: "100%",
  serverUrl: "https://api.6ocbx.com/index/upload",
  UEDITOR_HOME_URL:
    process.env.NODE_ENV === "development" ? "/public/UEditor/" : "/UEditor/",
  // 上传文件接口
  // UEditor 资源文件的存放路径，通常Nuxt项目设置为/UEditor/即可
  // 配合最新编译的资源文件，你可以实现添加自定义Request Headers,详情https://github.com/HaoChuan9421/ueditor/commits/dev-1.4.3.3
  // headers: {
  //   Authorization: `Bearer ${cookie.get('token')}`,
  //   tenantId: cookie.get('tenantId')
  // },
  readonly: false,
  focus: true,
};

const formItemLayout = {
  labelCol: { span: 24 },
  wrapperCol: { span: 24 },
};

const fileList = ref([]);

const remove = (i) => {
  fileList.value = fileList.value.filter(function (_, index) {
    return index !== i;
  });
};

const beforeUpload = async (file) => {
  // fileList.value = [...(fileList.value || []), file];
  const form = new FormData();
  form.append("file", file);
  const res = await upload(form);
  fileList.value = [
    ...(fileList.value || []),
    {
      name: file.name,
      url: res?.data?.url,
    },
  ];
  console.log("file", fileList.value);

  return false;
};

const formState = ref({
  title: "",
  code: "",
  time: undefined,
  industry: undefined,
  infoid: undefined,
  position: undefined,
  content: "",
});

const rules = {
  title: [
    {
      required: true,
      message: "请输入",
      trigger: "change",
    },
  ],
  code: [
    {
      required: true,
      message: "请输入",
      trigger: "change",
    },
  ],
  time: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
  position: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
  industry: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
  infoid: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
};

const formRef = ref();

const confirm = (values: any) => {
  formRef.value
    .validate()
    .then(async () => {
      const formData = {};
      for (const key in formState.value) {
        if (key == "content") {
          formData.content = formState.value.content;
        } else {
          formData[key] = formState.value[key];
        }
      }

      formData.locality = formState.value.position?.[0];
      formData.city = formState.value.position?.[1] || 0;
      formData.attachfiles = fileList.value?.length == 0 ? [1] : fileList.value;
      formData.time = formState.value.time?.unix();

      console.log("formData", formData);
      let res;
      if (props.editId) {
        formData.nid = props.editId;
        res = await Inforeleaseedit(formData);
      } else {
        res = await Inforeleaseadd(formData);
      }

      console.log("res", res);
      if (res?.data?.code == 1) {
        message.success("操作成功");
        formRef.value.resetFields();
        formState.value = {
          title: "",
          code: "",
          time: undefined,
          industry: undefined,
          infoid: undefined,
          position: undefined,
          content: "",
        };
        fileList.value = [];

        const res3 = await Inforeleaseget_serial_number();
        formState.value.code = res3?.data?.data?.code;

        if (props.editId) {
          emit("back");
        }
      } else {
        message.error(res?.data?.msg);
      }
    })
    .catch((error) => {
      console.log("error", error);
    });
};

const cancel = () => {
  const code = formState.value.code;
  formRef.value.resetFields();
  console.log("formState.value");
  formState.value = {
    title: "",
    code: code,
    time: undefined,
    industry: undefined,
    infoid: undefined,
    position: undefined,
    content: "",
  };
  fileList.value = [];

  console.log("formState.value2", formState.value);
};

const emit = defineEmits(["back"]);

defineExpose({
  confirm,
  cancel,
});
const type = ref([]);
const tags = ref([]);

const before = async () => {
  const res = await searchgetInfomation();
  type.value = res?.data?.data;

  const res2 = await Inforeleasetags();
  tags.value = res2?.data?.data;

  if (props.editId) {
    const res3 = await Inforeleasedetail({ nid: props.editId });
    const data = res3?.data?.data || {};
    formState.value = {
      ...data,
      position:
        data?.city || data?.city == 0
          ? [data?.locality]
          : [data?.locality, data?.city],
      industry: data.industry + "",
      time: dayjs(data?.release_time_text),
    };
    fileList.value = data?.attachfiles ? JSON.parse(data?.attachfiles) : [];
  } else {
    const res3 = await Inforeleaseget_serial_number();
    formState.value.code = res3?.data?.data?.code;
  }
};
function arrayToTree(array) {
  // 创建一个映射，以便通过id快速访问元素
  const map = {};
  array.forEach((item) => (map[item.adcode] = { ...item, children: [] }));

  // 构建树
  const tree = [];
  array.forEach((item) => {
    const parent = map[item.parent];
    if (parent && ["country", "province", "city"].includes(item.level)) {
      // 如果找到了父元素，将当前元素添加到父元素的children数组中
      parent.children.push(map[item.adcode]);
    } else if (["country", "province", "city"].includes(item.level)) {
      // 如果没有父元素（即顶级元素），将当前元素添加到树中
      tree.push(map[item.adcode]);
    }
  });

  return tree;
}
onMounted(() => {
  const treeData = arrayToTree(area);
  areaTree.value = treeData;
  before();
});

const props = defineProps({
  editId: String,
});
</script>

<style lang="scss" scoped>
:deep(.ant-upload-wrapper) {
  display: flex;
  align-items: center;
  gap: 16px;
}

:deep(.ant-upload-list) {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}
:deep(.edui-editor) {
  width: 100% !important;
  height: 100% !important;
}
:deep(.edui-editor-bottomContainer) {
  // display: none!important;
}
// :deep(.edui-editor-iframeholder) {
//   height: 320px !important;
// }
</style>
